<?php

$serv = new swoole_server("0.0.0.0", 9500);

$serv->set(array(
    'worker_num' => 100,
    'task_worker_num' => 10, //MySQL Connect Num

    //'open_eof_check' => true,
    //'package_eof' => "\r\n\r\n",
    //'package_max_length' => 65535,
));

function my_onReceive($serv, $fd, $from_id, $data)
{
    //Taskwait is a one task，for ex pass a sql statement ;
    //Then blocking waits for SQL to complete.
    echo "Receive Data: ".$data.PHP_EOL ;
    $result = $serv->taskwait($data);
    if ($result !== false) {
        list($status, $db_res) = explode(':', $result, 2);
        if ($status == 'OK') {
            /*
             * The database operation is successful, 
             * executing the business logic code,  
             * which automatically releases the MySQL connection.
             */
            $serv->send($fd, json_encode($db_res)."\r");
            var_dump(strlen($db_res));
        } else {
            $serv->send($fd, $db_res);
        }
        return;
    } else {
        $serv->send($fd, "Error. Task timeout\n");
    }
}

function my_onTask($serv, $task_id, $from_id, $sql)
{
    static $link = null;
    if ($link == null) {
        //$link = mysqli_connect("10.10.83.175", "root", "root", "go_test");
        try{
            $dns = 'mysql:dbname=go_test;host=10.10.83.175' ;
            $link = new PDO($dns, "root", "root", array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_AUTOCOMMIT => 1));
            $link->query('SET NAMES ' . "UTF-8");
        } catch (PDOException $e){
            $link = null;
            $serv->finish("ER:" . "Connection failed:" . $e->getMessage());
            return ;
        }
        
    }

    $result = $link->query($sql);
    if (!$result) {
        $serv->finish("ER:" . "query sql error !");
        return;
    }

    if(preg_match("/^select/i", $sql)){
        $data = $result->fetchAll(2);
    }else{
        $data = $result;
    }

    //$data = $result->fetch_all(MYSQLI_ASSOC);
    $serv->finish("OK:" . serialize($data));
}

function my_onFinish($serv, $data)
{
    echo "AsyncTask Finish:Connect.PID=" . posix_getpid() . PHP_EOL;
}

$serv->on('Receive', 'my_onReceive');
$serv->on('Task', 'my_onTask');
$serv->on('Finish', 'my_onFinish');
$serv->start();